package edu.luc.cs413s13.team1.monsterm.remote;

import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import edu.luc.cs413s13.team1.monsterm.controller.MonstermController;
import edu.luc.cs413s13.team1.monsterm.model.common.Constants;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

/**
 * Save the score on the cloud
 */
public class MonstermRemoteStore extends AsyncTask<String, Void, Boolean>{
    private ProgressDialog dialog;

    public MonstermRemoteStore(MonstermController controller) {
    	this.dialog = new ProgressDialog((Context)controller);
    }
    
    @Override
    protected void onPreExecute() {
    	super.onPreExecute();
        this.dialog.setMessage("Please wait");
        this.dialog.show();
    }
    
	@Override
	protected Boolean doInBackground(String... params) {
		String scoreString = params[0]; 
		try {
	        String data = URLEncoder.encode("monsterm", "UTF-8") + "=" + 
	        		URLEncoder.encode(scoreString.toString(), "UTF-8");
	 
	        // Send data
	        URL url = new URL(Constants.SERVER_URL);
	        URLConnection conn = url.openConnection();
	        conn.setDoOutput(true);
	        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
	        wr.write(data);
	        wr.flush();
	 
	        // Get the response
	        conn.getInputStream();
	        wr.close();
		} catch (Exception e ) { 
			e.printStackTrace();
		}
		return false;
	}
	
	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		// Set the progress bar to invisible
        if (dialog.isShowing()) {
            dialog.dismiss();
        }

	}
	
}


